import HttpUtils from "@page/common/utils/HttpUtils";
import Uts from "@module/Uts";
import CommonUtils from "@page/common/utils/CommonUtils";
import UserApi from "@module/userApi";
import store from "@assets/store.png";
import msg from "@assets/msg.png";
import kefu from "@assets/kefu.png";
import qq from "@assets/qq.png";
import urlHook from "@page/common/utils/urlHook";
import InfoModal from "@page/common/modal/InfoModal";
import AccountManage from "@module/../P/pages/AccountManage";
import EventApi from "@module/EventApi";
import tri1 from "../../../../imgs/tri1.png";
import ZenUI from "../../../../components/ZenUI/ZenUI";
import ExConfig from "@module/ExConfig";

export default class LoginHeader extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            user: {
                niceName: ""
            },
            showStoreContent: false,
            modalMsg: "账号已过期，请重新登录"
        };
        let _self = this;
        function updateState(value) {
            _self.setState({
                user: value
            });
        }
        function updateEvent(value) {
            _self.toggleShiftAccount(value);
        }
        this.cleanEvent = EventApi.on("showShiftAccount", updateEvent);
        UserApi.addUserStateHook(updateState, "user");
    }

    componentDidMount() {
        if (!ExConfig.isLoginAndRegisterPage() && Uts.isLogin()) {
            this.getIdentity();
            this.getZDMenu();
        }
        if ($state.params.action == "logout") {
            // this.logout();
        }
        // if (global.hasLogin) {

        // this.getCookie()
        // }
    }

    getCookie() {
        let url = `/store/api/username`;
        let params = {};

        REST.get(url).then(
            res => {
                console.log(res);
                return;
                location.href = `#/`;
            },
            err => {}
        );
    }

    logout(cb) {
        console.log("logout ..");
        let logoutUrl = "/auth/oauth/logout";
        REST.post(logoutUrl, {}).then(
            function(data) {
                console.log(data);
                global.hasLogin = false;
                cb && cb();
            },
            function(error) {
                console.log(error);
                if (error && error.response && error.response.status == 401) {
                    global.hasLogin = false;
                    cb && cb();
                } else {
                    error && ZenUI.ST(error.message);
                }
                // cb && cb();
            }
        );
    }

    componentWillUpdate(nextProps, nextState) {
        if (global.hasLogin) {
            this.getZDMenu();
        }
    }

    componentWillUnmount() {
        this.cleanEvent();
    }

    toggleShiftAccount(value) {
        if (value != this.state.showShiftAccount) {
            this.setState({
                showShiftAccount: value
            });
        }
    }

    getIdentity() {
        let goToLogin = () => {
            this.infoModal.showModal();
            CookieUtils.clearAllCookiesAndStorage();
            Uts.setCookie("accrosToken", "");
            setTimeout(() => {
                window.location.href = urlHook.login;
            }, 2000);
        };
        HttpUtils.getIdentity()
            .then(res => {
                console.log(res);

                if (res.user) {
                    Uts.storage.set(
                        "STORE_USERPERMISSION",
                        Uts.fetchObjectArrayToStringArray(
                            res.user.permissions,
                            "name"
                        )
                    );
                    Uts.setCookieMt({
                        id: res.user.id,
                        username: res.user.realName,
                        organization: res.user.organization.name,
                        orgId: res.user.organization.id,
                        vm: res.user.mobile,
                        userEmail: res.user.email,
                        orgCode: res.user.organization.code
                    });
                    global.hasLogin = true;
                    UserApi.updateUserState(res.user);
                    EventApi.emit("getIdentity", true);
                }
                if (res.code == "1020") {
                    goToLogin();
                }
            })
            .catch(err => {
                if (err && err.response && err.response.status == 401) {
                    goToLogin();
                }
                console.log(err);
            });
    }

    getZDMenu() {
        //if($.cookie('orgId') == 3)
        if (Uts.getCookie("orgId") == 3) {
            let _self = this;
            let url = "/store/api/order/succChoiceFundcard";
            // 暂时没有获取中大子系统域名地址的接口，先用这个用着。
            REST.post(url, { id: "1" }, "getInfo").then(
                function(d) {
                    //console.log(data);
                    if (d.code == "0000") {
                        Uts.setCookie("HREF_FOR_ZD", d.data.url);
                        _self.ZDUrl = d.data.url;
                        // $('#deploy-center').attr('href',d.data.url);
                    }
                },
                function(error) {
                    //console.log(error);
                }
            );
        }
    }

    render() {
        if (!global.hasLogin) {
            if (global.isSupp) {
                return <UnLoginForSupp />;
            }
            return <UnLoginHeader />;
        }
        const { niceName } = this.state.user;
        const { showStoreContent, modalMsg } = this.state;
        let premission = localStorage.getItem("STORE_USERPERMISSION");

        return (
            <div className={"login-header-wrapper"}>
                <div className={"login-header-content"}>
                    <div className={"login-header-left"}>
                        <div className={"login-header-username zen_ps-re"}>
                            嗨，
                            <span
                                onClick={() => {
                                    if (
                                        this.state.user.orgs &&
                                        this.state.user.orgs.length > 1
                                    ) {
                                        let showShiftAccountValue = !this.state
                                            .showShiftAccount;
                                        this.toggleShiftAccount(
                                            showShiftAccountValue
                                        );
                                    }
                                }}
                            >
                                {niceName}
                                {this.state.user.orgs &&
                                    this.state.user.orgs.length > 1 && (
                                        <span id="toggleAccount">
                                            <img
                                                className={"login-header-tri"}
                                                src={tri1}
                                                alt=""
                                            />
                                        </span>
                                    )}
                            </span>
                            {this.state.showShiftAccount && (
                                <AccountManage user={this.state.user} />
                            )}
                        </div>

                        <div
                            onMouseOver={() => {
                                this.setState({
                                    showStoreContent: true
                                });
                            }}
                            onMouseLeave={() => {
                                this.setState({
                                    showStoreContent: false
                                });
                            }}
                        >
                            <div className={"login-header-left-store"}>
                                <img src={store} alt="" />
                                我的关注
                            </div>
                            {showStoreContent && (
                                <div className={"login-header-left-store-box"}>
                                    <p
                                        onClick={() => {
                                            window.location.href =
                                                urlHook.store;
                                        }}
                                        className={
                                            "login-header-left-store-box-p1"
                                        }
                                    >
                                        我关注的宝贝
                                    </p>
                                    <p
                                        onClick={() => {
                                            window.location.href =
                                                urlHook.store + "/shop";
                                        }}
                                        className={
                                            "login-header-left-store-box-p2"
                                        }
                                    >
                                        我关注的店铺
                                    </p>
                                </div>
                            )}
                        </div>

                        <p
                            onClick={() => {
                                this.logout(function() {
                                    Uts.clearAllCookiesAndStorage();
                                    $state.go({
                                        stateName: "/Login"
                                    });
                                });
                            }}
                            className={"login-header-logout"}
                        >
                            退出
                        </p>
                    </div>
                    <div className={"login-header-right"}>
                        <p
                            onClick={() => {
                                $state.go({
                                    stateName: "/"
                                });
                            }}
                            className={"login-header-right-index"}
                        >
                            采购首页
                        </p>

                        {premission && premission.indexOf("采购人中心") > -1 && (
                            <p
                                onClick={() => {
                                    this.navToPurchaserCenter();
                                }}
                                className={"login-header-right-purchase"}
                            >
                                采购人中心
                            </p>
                        )}

                        {premission && premission.indexOf("HMS用户") > -1 && (
                            <p
                                onClick={() => {
                                    this.navToHmsCenter();
                                }}
                                className={"login-header-right-center"}
                            >
                                {Uts.getCookie("orgId") == 3
                                    ? "中大管理平台"
                                    : "管理中心"}
                            </p>
                        )}
                        {/*<a*/}
                        {/*    href="../purchaser/index.html#portal?directTo=pre"*/}
                        {/*    style={{ color: "rgb(0,140,208)" }}*/}
                        {/*    id="shift-version"*/}
                        {/*    className="zen_m-l-26"*/}
                        {/*>*/}
                        {/*    切换旧版*/}
                        {/*</a>*/}
                    </div>
                </div>
                <InfoModal
                    content={modalMsg}
                    getRef={v => (this.infoModal = v)}
                />
            </div>
        );
    }

    navToPurchaserCenter() {
        let permissions = Uts.storage.get("STORE_USERPERMISSION");

        if (permissions) {
            let userPermissions = permissions;
            var purchaser_limit = userPermissions.indexOf("采购人中心");
            var hospital_limit = userPermissions.indexOf("HMS用户");
            if (purchaser_limit == -1) {
                // this.setState({ modalMsg: "没有权限查看采购人中心" });
                // this.infoModal.showModal();
                ZenUI.ST("没有权限查看采购人中心", 3);
            } else {
                window.location.href = urlHook.purchaserManager;
            }
        } else {
            ZenUI.ST("获取权限失败，请刷新重试", 3);
        }
    }

    navToHmsCenter() {
        let permissions = Uts.storage.get("STORE_USERPERMISSION");
        if (permissions) {
            let userPermissions = permissions;
            var purchaser_limit = userPermissions.indexOf("采购人中心");
            var hospital_limit = userPermissions.indexOf("HMS用户");
            if (hospital_limit == -1) {
                // this.setState({ modalMsg: "没有权限进入管理中心" });
                // this.infoModal.showModal();
                ZenUI.ST("没有权限进入管理中心", 3);
            } else {
                let url;
                if (Uts.getCookie("orgId") == 3) {
                    url = this.ZDUrl;
                } else {
                    url = urlHook.purserCenter();
                }
                window.location.href = url;
            }
        } else {
            ZenUI.ST("获取权限失败，请刷新重试", 3);
        }
    }
}

class UnLoginForSupp extends React.Component {
    render() {
        let premission = localStorage.getItem("STORE_USERPERMISSION");
        let orgName = Uts.getCookie("username1");

        return (
            <div className={"login-header-wrapper"}>
                <div className={"login-header-content"}>
                    <div className={"login-header-left"}>
                        <div className={"zen_ps-re"}>
                            嗨，
                            <span>{decodeURIComponent(orgName)}</span>
                        </div>
                        <p
                            onClick={() => {
                                Uts.clearAllCookiesAndStorage();
                                window.location.href = urlHook.login;
                            }}
                            className={"login-header-logout"}
                        >
                            退出
                        </p>
                    </div>
                    <div className={"login-header-right"}>
                        <p
                            onClick={() => {
                                $state.go({
                                    stateName: "/"
                                });
                            }}
                            className={"login-header-right-index"}
                        >
                            采购首页
                        </p>
                        <p
                            onClick={() => {
                                location.href = `../supplier/index.html`;
                            }}
                            className={"login-header-right-purchase"}
                        >
                            供应商中心
                        </p>
                    </div>
                </div>
            </div>
        );
    }
}

class UnLoginHeader extends React.Component {
    render() {
        return (
            <div className={"login-header-wrapper"}>
                <div className={"login-header-content"}>
                    <div className={"unlogin-header-left"}>
                        <p
                            onClick={() => {
                                CommonUtils.addFavorite(this);
                            }}
                            className={"unlogin-header-store"}
                        >
                            收藏本站
                        </p>
                        <p
                            onClick={() => {
                                window.location.href = urlHook.login;
                            }}
                            className={"unlogin-header-login"}
                        >
                            登录
                        </p>
                        <span className={"unlogin-header-login-line"} />
                        <p
                            onClick={() => {
                                $state.go({
                                    stateName: "/register",
                                    params: {
                                        step: 1,
                                        registerType: 2
                                    }
                                });
                            }}
                            className={"unlogin-header-register"}
                        >
                            供应商注册
                        </p>
                        {/*<a
                            href="../purchaser/index.html#providerfirst?key=login"
                            className={"unlogin-header-register"}
                        >
                            供应商注册
                        </a>*/}
                        {/*<span*/}
                        {/*    className={"unlogin-header-login-line zen_m-l-15"}*/}
                        {/*/>*/}
                        {/*<a*/}
                        {/*    href="../purchaser/index.html?directTo=pre"*/}
                        {/*    style={{ color: "rgb(0,140,208)" }}*/}
                        {/*    id="shift-version"*/}
                        {/*    className="zen_m-l-15"*/}
                        {/*>*/}
                        {/*    切换旧版*/}
                        {/*</a>*/}
                    </div>
                    <div className={"unlogin-header-right"}>
                        <p className={"unlogin-header-right-welcome"}>
                            嗨，欢迎来到锐竞采购平台！
                        </p>
                        <div className={"unlogin-header-right-phone"}>
                            <img src={kefu} alt="" />
                            客服电话：4009005786
                        </div>
                        <a
                            href={`tencent://message/?uin=2448328732&Site=%E5%9C%A8%E7%BA%BFQQ&Menu=yes`}
                            className={"unlogin-header-right-qq"}
                        >
                            <img src={qq} alt="" />
                            <p>客服QQ</p>
                        </a>
                    </div>
                </div>
            </div>
        );
    }
}
